#include "myList.h"
#include <stdio.h> 
#include <stdlib.h>
#include <string.h>

Node* CreateList(int length)
{
    printf("** Node* CreateList(int length)\n");

    //判读长度
    if(length <= 0)
    {
        printf("Length Error\n");
        return NULL;
    }

    //开始创建
    //1 创建头指针，为指针
    Node *phead,*prear;
    phead=prear=NULL;

    //2、申请内存：头结点
    phead=(Node*)malloc(sizeof(Node));

    //3、处理异常情况
    if(NULL==phead)
    {
        perror("malloc failed!\n");
        exit(EXIT_FAILURE);
    }

    //4、给头结点初值
    //(*phead).pnext=NULL;
    phead->pnext=NULL;
    phead->num=0;

    //5、尾指针
    prear=phead;
    
    //6、向头结点后面添加节点
    Node* pNewNod=NULL;
    DataType n=0;
    for(int i=0;i<length;i++)
    {
        //6.1  申请一个节点，检测，给值
        pNewNod=(Node*)malloc(sizeof(Node));
        if(NULL==pNewNod)
        {
            perror("malloc failed!\n");
            exit(EXIT_FAILURE);
        }
        pNewNod->pnext=NULL;
        printf("input num:");
        scanf("%d",&n);
        pNewNod->num=n;

        //6.2 将新申请的结点添加到链表中，作为新的尾节点
        prear->pnext=pNewNod;
        prear=pNewNod;
    }
    return phead;
}

void TraverseList(const Node* const pList)
{
    //从首元节点
    Node* ptemp=pList->pnext;
    if(NULL==ptemp)
    {
        printf("List is Null!\n");
    }
    printf("Now List Data:\n");
    while(ptemp)
    {
        printf("%d ",ptemp->num);
        ptemp=ptemp->pnext;
    }
    printf("\n");
}

Node* InsertElement(Node* pList,Node* pos,DataType val)
{
    Node* ptemp=(Node*)malloc(sizeof(Node));
    if(ptemp==NULL) 
    {
        printf("malloc failed!\n");
        return pList;
    }

    ptemp->num=val;
    ptemp->pnext=pos->pnext;
    pos->pnext=ptemp;
    return pList;
}


Node* DeleteElement(Node* pList,DataType val)
{
    Node* ptemp=pList;
    Node* pos=NULL;
    while(ptemp->pnext!=NULL && ptemp->pnext->num != val)
    {
        ptemp=ptemp->pnext;
    }
    if(ptemp->pnext==NULL)
    {
        printf("Data not found\n");
    }
    else
    {
        pos=ptemp->pnext;
        ptemp->pnext=pos->pnext;      
        //ptemp->pnext=ptemp->pnext->pnext;

        free(pos);
        pos=NULL;
    }

    return pList;
}

Node* FindElement(Node* pList,DataType val)
{
    Node* p=pList->pnext;
    if(NULL==p)
    {
        printf("kong!\n");
        return NULL;
    }

    while(p!=NULL &&p->num!=val)
    {
        p=p->pnext;
    }

    printf("Find Data:%d!\n",p->num);

    return p;
}

Node* ChangeElement(Node* pos,DataType val)
{
    pos->num=val;
}